package com.wenyu.wenyuyuedu.fragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.MainActivity;
import com.wenyu.wenyuyuedu.activity.personage.AlertsActivity;
import com.wenyu.wenyuyuedu.activity.personage.IdeaAndFeedBackActivity;
import com.wenyu.wenyuyuedu.activity.personage.MyCollectActivity;
import com.wenyu.wenyuyuedu.activity.personage.MyPublishActivity;
import com.wenyu.wenyuyuedu.activity.personage.SelectHeadActivity;
import com.wenyu.wenyuyuedu.activity.personage.SettingActivity;
import com.wenyu.wenyuyuedu.activity.personage.Wallet_Activity;
import com.wenyu.wenyuyuedu.bean.WXPlayBean;
import com.wenyu.wenyuyuedu.bean.personage.JudgeLoginBean;
import com.wenyu.wenyuyuedu.bean.personage.PersonageBeginBean;
import com.wenyu.wenyuyuedu.bean.personage.ShowHeadNicknameBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.WXPlayServer;
import com.wenyu.wenyuyuedu.server.personage.JudgeLoginServer;
import com.wenyu.wenyuyuedu.server.personage.PersonageBeginServer;
import com.wenyu.wenyuyuedu.server.personage.ShowHeadNicknameServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.view.CircleImageView;
import com.wenyu.wenyuyuedu.wxapi.MD5;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 我的
 */
public class PersonageFragment extends Fragment implements View.OnClickListener {


    @InjectView(R.id.ci_personage_head)
    CircleImageView ciPersonageHead;    //头像的id
    @InjectView(R.id.rl_set)
    RelativeLayout rlSet;               //设置的id
    @InjectView(R.id.rl_publish)
    RelativeLayout rlPublish;           //通知消息的id
    @InjectView(R.id.rl_collect)
    RelativeLayout rlCollect;           //我的动态的id
    @InjectView(R.id.rl_wallet)
    RelativeLayout rlWallet;            //我的收藏的id
    @InjectView(R.id.rl_money)
    RelativeLayout rlMoney;             //钱包的id
    @InjectView(R.id.rl_help)
    RelativeLayout rlHelp;              //帮助与反馈的id
    @InjectView(R.id.tv_personage_name)
    TextView tvPersonageName;
    @InjectView(R.id.message_count)
    TextView messageCount;
    @InjectView(R.id.iv_wallet)
    ImageView ivWallet;
    @InjectView(R.id.iv_circle)
    ImageView ivCircle;
    @InjectView(R.id.iv_set)
    ImageView ivSet;
    @InjectView(R.id.iv_help)
    ImageView ivHelp;
    private View personageView;
    private Intent intent;
    private IWXAPI msgApi;
    private String token;
    private int code;

    public PersonageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        personageView = inflater.inflate(R.layout.fragment_personage, container, false);
        FragmentActivity activity = getActivity();
        ButterKnife.inject(this, personageView);
        msgApi = WXAPIFactory.createWXAPI(activity, "wx645768d32ba61b12", true);
        msgApi.registerApp("wx645768d32ba61b12");
        initView();
        // requestHeadNickname();
        return personageView;
    }

    @Override
    public void onStart() {
        super.onStart();
        requestHeadNickname();
        judegeToken();
        messageCountData();
        StatusBarUtil.setStatusBar(getActivity(), R.color.personage_statue);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    /*展示头像昵称*/
    private void requestHeadNickname() {
        ShowHeadNicknameServer showHeadNicknameServer = ApiWrapper.getInstance().create(ShowHeadNicknameServer.class);
        Call<ShowHeadNicknameBean> headNickname = showHeadNicknameServer.getHeadNickname(token);
        headNickname.enqueue(new Callback<ShowHeadNicknameBean>() {
            @Override
            public void onResponse(Call<ShowHeadNicknameBean> call, Response<ShowHeadNicknameBean> response) {
                ShowHeadNicknameBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        if (body.getInfo().getNickname() != null) {
                            tvPersonageName.setText(body.getInfo().getNickname());
                            AbSharedUtil.putString(getActivity(),SharedConstants.USER_NICKNAME,body.getInfo().getNickname());
                        }
                        if (body.getInfo().getIcon() != null) {
                            Glide.with(getActivity())
                                    .load(body.getInfo().getIcon())
                                    .error(R.drawable.login_logo)
                                    .into(ciPersonageHead);
                        }
                        AbSharedUtil.putString(getActivity(), SharedConstants.USER_NICKNAME, tvPersonageName.getText().toString());
                    } else if (code == 0) {
                        showLoginDoalog();
                    } else if (code == 5001) {
                        MyToast.showToast(getActivity(), "系统繁忙", Toast.LENGTH_SHORT);
                    } else if (code == 5000) {
                        showLoginDoalog();
                    }
                }
            }

            @Override
            public void onFailure(Call<ShowHeadNicknameBean> call, Throwable t) {
                MyToast.showToast(getActivity(), "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    /*获取消息通知的数量*/
    private void messageCountData() {
        String token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        PersonageBeginServer personageBeginServer = ApiWrapper.getInstance().create(PersonageBeginServer.class);
        Call<PersonageBeginBean> begin = personageBeginServer.getBegin(token, 3);
        begin.enqueue(new Callback<PersonageBeginBean>() {
            @Override
            public void onResponse(Call<PersonageBeginBean> call, Response<PersonageBeginBean> response) {
                PersonageBeginBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        int informNum = body.getInfo().getInformNum();
                        if (informNum > 0) {
                            messageCount.setText(informNum + "");
                            messageCount.setVisibility(View.VISIBLE);
                        } else {
                            messageCount.setVisibility(View.INVISIBLE);
                            /*隐藏我的右上角的小红点*/
                            MainActivity activity = (MainActivity) getActivity();
                            activity.setInformRedHide();
                        }
                    } else if (code == 0) {
                        // showLoginDoalog();
                    }
                }
            }

            @Override
            public void onFailure(Call<PersonageBeginBean> call, Throwable t) {
                MyToast.showToast(getActivity(), "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    /*
    * 初始化控件的点击事件
    * */
    private void initView() {
        intent = new Intent();
        token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        ciPersonageHead.setOnClickListener(this);
        rlPublish.setOnClickListener(this);
        rlCollect.setOnClickListener(this);
        rlWallet.setOnClickListener(this);
        rlMoney.setOnClickListener(this);
        rlSet.setOnClickListener(this);
        rlHelp.setOnClickListener(this);
        if (token == null || token.equals("")) {
            tvPersonageName.setText("未登录");
            ciPersonageHead.setImageResource(R.drawable.login_logo);
        } else {

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*
            * 更改头像昵称
            * */
            case R.id.ci_personage_head:
                if (code == 1) {
                    intent.setClass(getActivity(), SelectHeadActivity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }
                break;
            //消息通知
            case R.id.rl_publish:
                if (code == 1) {
                    intent.setClass(getActivity(), AlertsActivity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }
                break;
            //我的动态
            case R.id.rl_collect:
                if (code == 1) {
                    intent.setClass(getActivity(), MyPublishActivity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }

                break;
            //我的收藏
            case R.id.rl_wallet:
                if (code == 1) {
                    intent.setClass(getActivity(), MyCollectActivity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }

                // requestData();
                break;
            //钱包
            case R.id.rl_money:
                if (code == 1) {
                    intent.setClass(getActivity(), Wallet_Activity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }

                break;
            /*
            * 设置
            * */
            case R.id.rl_set:
                intent.setClass(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;
            /*
            * 帮助与反馈
            *
            * */
            case R.id.rl_help:
                if (code == 1) {
                    intent.setClass(getActivity(), IdeaAndFeedBackActivity.class);
                    startActivity(intent);
                } else if (code == 0) {
                    showLoginDoalog();
                } else if (code == 5000) {
                    showLoginDoalog();
                }

                break;
            default:
                break;
        }
    }


    /*判断token是否登陆时候过时*/
    public void judegeToken() {
        JudgeLoginServer judgeLoginServer = ApiWrapper.getInstance().create(JudgeLoginServer.class);
        Call<JudgeLoginBean> judgeLogin = judgeLoginServer.getJudgeLogin(token);
        judgeLogin.enqueue(new Callback<JudgeLoginBean>() {
            @Override
            public void onResponse(Call<JudgeLoginBean> call, Response<JudgeLoginBean> response) {
                JudgeLoginBean body = response.body();
                code = body.getCode();
           /*     MyToast.showToast(getActivity(), "网络异常，请重新登陆!" + code, Toast.LENGTH_SHORT);
                if (code == 1) {

                } else if (code == 0) {
                    showLoginDoalog();
                }*/
            }

            @Override
            public void onFailure(Call<JudgeLoginBean> call, Throwable t) {
                MyToast.showToast(getActivity(), "网络异常，请重新登陆!" + t, Toast.LENGTH_SHORT);
                System.out.println("PersonageFragment: " + t);
            }
        });
    }

    /*调起微信支付*/
    private void requestData() {
        WXPlayServer wxPlayServer = ApiWrapper.getInstance().create(WXPlayServer.class);
        Call<WXPlayBean> wxPlay = wxPlayServer.getWxPlay("475331a2b6dc0beeda9ae881c3229c14", 186 + "", 125 + "", 2 + "", 0.01 + "");
        wxPlay.enqueue(new Callback<WXPlayBean>() {
            @Override
            public void onResponse(Call<WXPlayBean> call, Response<WXPlayBean> response) {
                WXPlayBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    System.out.println("PersonageFragment: " + code);
                    if (code == 1) {
                        MyToast.showToast(getActivity(), "微信支付", Toast.LENGTH_SHORT);
                        PayReq req = new PayReq();
                        req.appId = body.getInfo().getAppid();//appid
                        req.partnerId = body.getInfo().getPartnerid();//商户号
                        req.prepayId = body.getInfo().getPrepayid();//预支付回话id
                        req.nonceStr = body.getInfo().getNoncestr();//随机字符串
                        req.timeStamp = body.getInfo().getTimestamp();//时间戳
                        req.packageValue = "Sign=WXPay";//固定值
                        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                        signParams.add(new BasicNameValuePair("appid", req.appId));
                        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
                        signParams.add(new BasicNameValuePair("package", req.packageValue));
                        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
                        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
                        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
                       /* String s = genAppSign(signParams);
                        System.out.println("PersonageFragment: " + s);
                        req.sign = genAppSign(signParams);*///签名

                        req.sign = body.getInfo().getSign();
                        req.extData = "ext data"; // optional
                        msgApi.sendReq(req);
                    }
                }
            }

            @Override
            public void onFailure(Call<WXPlayBean> call, Throwable t) {
                MyToast.showToast(getActivity(), "网络异常，请稍后重试", Toast.LENGTH_SHORT);
                System.out.println("PersonageFragment: " + t);
            }
        });
    }

    /*获取时间戳*/
    public String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        /*这里的key是商户设置的key*/
        sb.append("2c9fe01e6692efef152ee01b23e67857");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new AlertDialog.Builder(getActivity()).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(getActivity(), SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
                ad.dismiss();
            }
        });
    }
}
